<?php

namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_product\Entity\ShusyProductStandard;
use Drupal\shusy_product_miaosha\Entity\ShusyProductMiaoshaStandard;
use Exception;

/**
 * @OA\Schema(
 *   schema="MsProductItem",
 *   type="object",
 *   description="MsProductItem",
 *   allOf={
 *       @OA\Schema(ref="#/components/schemas/ProductItem"),
 *   }
 * )
 */
class MsProductItem extends ProductItem {

  protected function setValue() {
    parent::setValue();
    $stock = 0;
    $totalStock = 0;
    $es = shusy_product_standard_load_multiple(FALSE, [
      'product_id' => $this->entity->id,
      'status' => 1,
    ]);
    foreach ($es as $e) {
      if ($e instanceof ShusyProductStandard) {
        try {
          $ew = $e->wrapper();
          $miaosha = $ew->miaosha->value();
          if ($miaosha instanceof ShusyProductMiaoshaStandard && $miaosha->status == 1) {
            $totalStock += $miaosha->stock;
          }
          $stock += $ew->stock->value();
        } catch (Exception $exception) {
          watchdog_exception(__FUNCTION__, $exception);
        }
      }
    }

    $progress = ($stock / $totalStock);

    $value = [
      /**
       * @OA\Property(
       *   property="stock",
       *   type="integer",
       *   description="秒杀剩余库存",
       * ),
       */
      'stock' => (int) $stock,
      /**
       * @OA\Property(
       *   property="progress",
       *   type="integer",
       *   description="秒杀进度条 0 - 100",
       * ),
       */
      'progress' => (int) $progress,
    ];
    $this->merge($value);
  }

}
